<template>
  <!-- 工作台相关 -->
  <div class="go-editComponent">
    <div class="editComponentStats">
      <div class="editComponentStatsChart">
        <div class="height_title">
          <div class="title">组件类型</div>
        </div>

        <n-scrollbar trigger="none">
          <div class="StatsChartscrollbar">
            <n-tooltip trigger="hover" v-for="(item, index) in chartData" :key="index">
              <template #trigger>
                <n-button @click="handleComponent(item)">
                  <template #icon>
                    <component :is="item.icon"></component>
                  </template>
                </n-button>
              </template>
              {{ item.name }}
            </n-tooltip>
          </div>
        </n-scrollbar>
      </div>
      <div>
        <template v-if="targetData.data.targetComponentData">
          <div v-if="targetData.data.targetComponentData.render == ComponentBiType.TABLES2"
           class="editComponentStatsArgument">
            <div class="height_title">
              <div class="title">维度选择</div>
            </div>

            <div class="editComponentcolumnsitem">
              <div class="FieldBox">
                <div v-if="targetData.data.targetComponentData.type == ComponentBiDataType.PIVOT_TABLE">
                  <div class="height_title">
                    <div class="title">行头</div>
                  </div>
                  <draggable
                    v-model="targetData.data.options.fields.rows"
                    group="columns1"
                    data-dargId="rows"
                    class="boxSize"
                    animation="300"
                    itemKey="field"
                    @end="onEnd"
                  >
                    <template #item="{ element }">
                      <div class="columnsitem FileBg" :data-data="JSON.stringify(element)">
                        <component :is="element.prefix"></component>
                        <span style="margin-left: 5px">{{ element.name }}</span>
                      </div>
                    </template>
                  </draggable>
                </div>
                <div>
                  <div class="height_title">
                    <div class="title">列头</div>
                  </div>
                  <draggable
                    data-dargId="columns"
                    class="boxSize"
                    v-model="targetData.data.options.fields.columns"
                    @end="onEnd"
                    group="columns1"
                    animation="300"
                    itemKey="field"
                  >
                    <template #item="{ element }">
                      <div class="columnsitem FileBg" :data-data="JSON.stringify(element)">
                        <!-- <component :is="element.prefix"></component> -->
                        <span style="margin-left: 5px">{{ element.name }}</span>
                      </div>
                    </template>
                  </draggable>
                </div>
              </div>
              <div class="valueBox" v-if="targetData.data.targetComponentData.type == ComponentBiDataType.PIVOT_TABLE">
                <div class="height_title">
                  <div class="title">指标</div>
                </div>
                <draggable
                  v-model="targetData.data.options.fields.values"
                  @end="onEnd"
                  class="boxSize"
                  data-dargId="values"
                  group="columns1"
                  animation="300"
                  itemKey="field"
                >
                  <template #item="{ element }">
                    <div class="columnsitem ValueBg" :data-data="JSON.stringify(element)">
                      <!-- <component :is="element.prefix"></component> -->
                      <span style="margin-left: 5px">{{ element.name }}</span>
                    </div>
                  </template>
                </draggable>
              </div>
            </div>
          </div>

          <div v-else-if="targetData.data.targetComponentData.render == ComponentBiType.COMMONCHARTS">
           <div class="height_title">
              <div class="title">维度选择</div>
            </div>
              <!-- 目前维度都是单选 -->
                    <div class="mt20">
                      <n-select
          filterable
        v-model:value="dimensionality"
          placeholder="请选择 数据集"
          :options="targetData.data.colums"
          value-field="field"
          label-field="name"
          :on-update:value="handleSelectdimensionality"
        />
                    </div>
          <div class="height_title mt20">
              <div class="title">指标</div>
            </div>
            <div class="mt20">
                                  <n-select
          v-model:value="indicator"
          filterable
          :multiple="targetData.data.targetComponentData.multiple" 
          placeholder="请选择 数据集"
          :options="targetData.data.colums"
          value-field="field"
          label-field="name"
          :on-update:value="handleSelectindicator"
        />
            </div>
          </div>
        </template>

        <template v-else>
          <n-empty size="large" description="请选择组件类型"> </n-empty>
        </template>
      </div>
    </div>
    <div class="editComponentContent">
      <n-spin :show="!Refresh" class="w100 h100 ">
        <template v-if="Refresh">
          <tableS2
            v-if="targetData.data.targetComponentData && targetData.data.targetComponentData.render == ComponentBiType.TABLES2"
            :s2DataConfig="targetData.data.options"
            :type="targetData.data.targetComponentData.type"
          ></tableS2>
            <commonCharts
            v-else-if="targetData.data.targetComponentData 
            && targetData.data.targetComponentData.render == ComponentBiType.COMMONCHARTS"
            :s2DataConfig="targetData.data.chartConfig"
            :type="targetData.data.targetComponentData.type"
          ></commonCharts>
         <div v-else class="aic jcc fdc h100">
           <n-result  status="404" title="请点击组件类型" description="生活总归带点绿"> </n-result>
         </div>
        </template>
      </n-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
//数据集
import { ref, watch } from 'vue'
import { PieChartSharp, PulseSharp, PodiumSharp, Newspaper, ReorderFour } from '@vicons/ionicons5'
import { renderIcon } from '@/utils'
import tableS2 from './tableS2/index.vue'
import commonCharts from './Common/index.vue'
import optionsCommon from './index'
import { useThemeVars } from 'naive-ui'
import Draggable from 'vuedraggable'
import { ComponentBiDataType, ComponentBiType, TabsBottomType } from '@/enums/editReportEnum'
import { useTargetData } from '@/views/Bi/hooks/useTargetData'
const themeVars = useThemeVars()
const emit = defineEmits(['updataDataBase'])
const props = defineProps({
  targetData: {
    type: Object,
    required: true
  }
})

const chartData = ref([
  {
    name: '多维表格',
    render: ComponentBiType.TABLES2,
    type: ComponentBiDataType.PIVOT_TABLE,
    icon: renderIcon(Newspaper)
  },
  {
    name: '普通表格',
    render: ComponentBiType.TABLES2,
    type: ComponentBiDataType.TABLE,
    icon: renderIcon(ReorderFour)
  },
  {
    name: '饼状图',
    render: ComponentBiType.COMMONCHARTS,
    type: ComponentBiDataType.PIE,
    icon: renderIcon(PieChartSharp),
    multiple:false,
    option:optionsCommon.pieOption

  },
  {
    name: '折线图',
    render: ComponentBiType.COMMONCHARTS,
    type: ComponentBiDataType.LINE,
    icon: renderIcon(PulseSharp),
        multiple:true,
       option:optionsCommon.LineOption
  },
  {
    name: '柱状图',
    render: ComponentBiType.COMMONCHARTS,
    type: ComponentBiDataType.BAR,
    icon: renderIcon(PodiumSharp),
      multiple:true,
       option:optionsCommon.BarOption
  }
])
const onEnd = (e: any) => {
  // console.log('e :>> ', e);
  //   const {dataset} = e.target
  //  const datasetTo = e.to.dataset
  //   if(datasetTo.dargid!='values'&&datasetTo.dargid!='columns'
  //   &&datasetTo.dargid!='rows'){
  //     //吧拖拽数据返回到 字段列表
  //   }else{
  //       console.log('dataset :>> ',e.item.dataset, dataset);
  //   }
}
const dimensionality = ref(null)
const indicator = ref(null)
/**
 * 选择维度  单选 默认第一个
 */
const handleSelectdimensionality= (value: any)=>{

  const { targetData } = useTargetData()
        dimensionality.value =value
      if(dimensionality.value==null){
          targetData.value.data.chartConfig.dataset.dimensions= [value]
      }else{
          targetData.value.data.chartConfig.dataset.dimensions[0]= value
      }
//设置 source 数据
        initSource()
}
/**
 * 初始化数据
 * dataArr 数据
 */
const initSource=()=>{
  const { targetData } = useTargetData()
      let sourceArr = [];
    let dataArr = targetData.value.data.options.data
      for (let index = 0; index < dataArr.length; index++) {
      const element = dataArr[index];
      const objData:any = {}
      for (let index = 0; index < targetData.value.data.chartConfig.dataset.dimensions.length; index++) {
        const dimensionsElement = targetData.value.data.chartConfig.dataset.dimensions[index];
        objData[dimensionsElement] =element[dimensionsElement]
      }
      sourceArr.push(objData)
    }
      targetData.value.data.chartConfig.dataset.source = sourceArr
      console.log('targetData.value.data.chartConfig :>> ', targetData.value.data);
       const dimensionsElement = targetData.value.data.chartConfig.dataset.dimensions[0];
      if(targetData.value.data.targetComponentData.type=='line'||targetData.value.data.targetComponentData.type=='bar'){
            targetData.value.data.chartConfig.xAxis.data = sourceArr.map(res=>{
                return res[dimensionsElement]
            })  
            //初始化 series
            const series = targetData.value.data.chartConfig.series[0]
            const forNum = targetData.value.data.chartConfig.dataset.dimensions.length
            if(forNum==1)return
            const newSeries = []
            for (let index = 0; index < targetData.value.data.chartConfig.dataset.dimensions.length; index++) {
              const element = targetData.value.data.chartConfig.dataset.dimensions.length[index];
              if(index>0){
                newSeries.push(series)
              }
              
            }
            targetData.value.data.chartConfig.series = newSeries
      }
}
/**
 * 选择指标
 */
const handleSelectindicator= (val:any)=>{
     indicator.value =val
     
     const { targetData } = useTargetData()
     
      if(!dimensionality.value){
           window['$message'].warning(`请先选择维度...`)
        return
      }
      let data =  targetData.value.data.chartConfig.dataset.dimensions[0]
        if(props.targetData.data.targetComponentData.multiple){
            targetData.value.data.chartConfig.dataset.dimensions = [data].concat(val)
      }else{
          let arr = [data]
             arr.push(val)
             targetData.value.data.chartConfig.dataset.dimensions = arr
      }
    //设置 source 数据
        initSource()

}
//表格监听数据 start
watch(
  () => props.targetData,
  data => {
    console.log('rows :>> ', data)
  },
  {
    deep: true,
    immediate: true
  }
)
//表格监听数据 end
const targetComponentData = ref(null)
const Refresh = ref(true)
const handleComponent = (item: any) => {
  //更新数据集 初始化数据 
  emit('updataDataBase')
  // console.log('props.targetData.data.options :>> ', props.targetData.data);
  if (props.targetData.data.options.id) {
      Refresh.value = false
      //目标组件信息
    props.targetData.data.targetComponentData = item
     props.targetData.data.chartConfig = item.option
    setTimeout(() => {
      Refresh.value = true
    }, 300)
  } else {
    window['$message'].warning(`请选择数据集...`)
  }
}
</script>
<style lang="scss">
.n-spin-content{
  height: 100%;
}
.h100 {
  overflow-y: scroll;
  height: 100%;
}
.boxSize {
  overflow-y: scroll;
  padding: 10px;
  box-sizing: border-box;
  background-color: v-bind('themeVars.modalColor');
  margin-top: 10px;
  border-radius: v-bind('themeVars.borderRadius');
  height: 150px;
  min-height: calc(100% - 32px);
  border: 1px solid v-bind('themeVars.borderColor');
}
</style>
<style lang="scss" scoped>
@include go('editComponent') {
  display: grid;
  grid-template-columns: 350px 1fr;
  padding: 10px;
  box-sizing: border-box;
  height: 100%;
  background-color: v-bind('themeVars.bodyColor');
  .editComponentStats {
    padding: 5px;
    display: grid;
    grid-template-rows: 300px 1fr;
    background-color: v-bind('themeVars.cardColor');
    .editComponentStatsChart {
      height: 100%;
      .StatsChartscrollbar {
        display: grid;
        grid-gap: 10px;
        margin-top: 15px;
        grid-template-columns: 1fr 1fr 1fr 1fr;
      }
    }
    .editComponentStatsArgument {
      height: 100%;
      display: grid;
      grid-template-rows: 22px 1fr;
      .editComponentcolumnsitem {
        display: grid;
        grid-template-columns: 1fr 1fr;
        height: 100%;
        box-sizing: border-box;
        padding: 10px;
        grid-column-gap: 10px;
        .FieldBox {
          display: grid;
          grid-gap: 10px;

          grid-template-rows: 1fr 1fr;
        }
        .valueBox {
        }
      }
    }
  }
  .editComponentContent {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.height_title {
  .title {
    padding: 0 10px;
    border-left: 3px solid v-bind('themeVars.primaryColor');
    font-size: 14px;
    color: v-bind('themeVars.textColor1');
  }
}
.FileBg {
  background-color: v-bind('themeVars.primaryColor');
  color: #fff;
}
.ValueBg {
  background-color: v-bind('themeVars.successColor');
  color: #fff;
}
</style>
